import datetime

from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from  django.conf import settings

from web import models
from web.models import UserInfo


class Tracer():
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None

class AuthMiddleware(MiddlewareMixin):

    #面向切面编程
    # 实现白名单URL访问 和 用户登录情况及其会员策略
    def process_request(self, request):

        try:
            tracer = Tracer()
            user_id = request.session.get('user_id',0)
            user_obj = UserInfo.objects.filter(id=user_id).first()
            tracer.user = user_obj
            request.tracer = tracer
        except Exception as e:
            print('您猜怎么着，崩了！')
            # pass#??? 泥载肝肾莫


        #白名单 未登录也可访问的url
        #访问的当前路径
        # print(request.path_info)

        if  request.path_info in settings.WHITE_URL_LIST:
            return

        if not  request.tracer.user:
            return  redirect(reverse('login'))

        # 当前用户的会员额度：
        # 方式1：免费额度在交易记录中储存
        #
        _object = models.Transaction.objects.filter(user=user_obj,status=2).order_by('-id').first()

        #盘吨是否一国企 是否过期
        current_date = datetime.datetime.now()

        if _object.end_datetime and _object.end_datetime < current_date:
            #expired
            # changed to FreeType
            _object = models.Transaction.objects.filter(user=user_obj, status=2,price_policy__category=1).first()


        tracer.price_policy = _object.price_policy
        request.tracer = tracer
            # print('auth.py price ok!')
        # 方式2: 免费的存储配置文件



    def process_view(self,request,view,args,kwargs):
        '''
        实现判断用户访问的路径 以确保项目配置信息等详细信息模板的适时装饰

        @param request:
        @param view:
        @param args:
        @param kwargs:
        @return:
        '''

        #获取路由的关键字参数的信息
        # 判断URL是否是manage 开头，在判断是否是当前用户创建、或者参与的project 防止非法访问

        if not request.path_info.startswith('/manage/'):
            return

        project_id = kwargs.get('project_id')
        # 是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            # 是我创建的项目的话，我就让他通过
            request.tracer.project = project_object
            return

        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            # 是我参与的项目
            request.tracer.project = project_user_object.project
            return

        return redirect('project_list')



